package com.zzyl.intercept;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: 前端拦截器
 * @Description: TODO
 * @DateTime: 2024/6/16 12:00
 **/
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取携带的authorization
        String token = request.getHeader(Constants.AUTHORIZATION);
        if(StrUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        try {
            Map<String, Object> claims = JwtUtil.parseJWT(jwtConfigProperties.getBase64EncodedSecretKey(),token);
            Object userId = claims.get(Constants.JWT_USERID);
            //往ThreadLocal中存入用户ID
            UserThreadLocal.setUserId(Long.valueOf(userId.toString()));
        } catch (Exception e) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //避免ThreadLocal的内存泄漏
        UserThreadLocal.removeUserId();
    }
}
